package fr.uparis10.miage.m1p1.global;

import java.util.HashSet;

public class UniqueIdManager {
	/* We'll hold here the unique class instance */
	private static UniqueIdManager theInstance = null;
	
	/* This Set is gonna hold the list of all Employee IDs: */
	private HashSet<Integer> mEmpIdSet = new HashSet<Integer>();
	/* Will hold the last generated Employee ID: */
	private int mLastEmpId = 0;
	/* This Set is gonna hold the list of all Social Security Numbers in the Enterprise: */
	private HashSet<Long> mNumSSSet = new HashSet<Long>();
	/* Holds the last generated Security Number ID: */
	private long mLastNumSS = 0;
	
	/**
	 * Private Constructor; we'll create a singleton class
	 */
	private UniqueIdManager() {
		
	}
	
	/**
	 * Gets the unique instance of the class
	 * @return
	 */
	public static UniqueIdManager getInstance() {
		if (theInstance == null) {
			/* First call - create the instance */
			theInstance = new UniqueIdManager();
		}
		return theInstance;
	}
	
	/**
	 * We'll generate a new Employee ID and register it
	 * @return
	 */
	public int createNewEmplId() {
		while (mEmpIdSet.contains(++mLastEmpId)); //skip already registered numbers, if any
		/* Register the new EMP_ID */
		mEmpIdSet.add(mLastEmpId);
		return mLastEmpId;
	}
	
	/**
	 * We'll try to use the desired Employee ID, otherwise generate one
	 * @param emplId
	 * @return
	 */
	public int createNewEmplId(int preferredEmplId) {
		if (preferredEmplId <= 0 || mEmpIdSet.contains(preferredEmplId)) {
			/* Generate an ID and return it */
			return createNewEmplId();
		}
		mEmpIdSet.add(preferredEmplId);
		return preferredEmplId;
	}
	
	/**
	 * Create a hew Numero Securite Sociale and register it
	 * @return
	 */
	public long createNewNumSS() {
		while (mNumSSSet.contains(++mLastNumSS)); //skip already registered numbers, if any
		mNumSSSet.add(mLastNumSS);
		return mLastNumSS;
	}
	
	/**
	 * Try to use the preferred SSID, and if fails - generate one
	 * @param preferedNumSS
	 * @return
	 */
	public long createNewNumSS(long preferredNumSS) {
		if (preferredNumSS <= 0 || mNumSSSet.contains(preferredNumSS)) {
			/* Generate a new SSID and return it */
			return createNewNumSS();
		}
		mNumSSSet.add(preferredNumSS);
		return preferredNumSS;		
	}
}
